<template>
  <div class="register-container">
    <div class="register-card">
      <div class="register-header">
        <h1>创建账户</h1>
        <p>注册新账户以开始使用AI 3D模型生成服务</p>
      </div>

      <form @submit.prevent="handleRegister" class="register-form">
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            id="username"
            v-model="form.username"
            type="text"
            placeholder="请输入用户名"
            required
            :disabled="loading"
            class="form-input"
            @blur="checkUsername"
          />
          <div v-if="usernameError" class="field-error">
            {{ usernameError }}
          </div>
        </div>

        <div class="form-group">
          <label for="email">邮箱</label>
          <input
            id="email"
            v-model="form.email"
            type="email"
            placeholder="请输入邮箱地址"
            required
            :disabled="loading"
            class="form-input"
          />
        </div>

        <div class="form-group">
          <label for="phone">电话号码</label>
          <input
            id="phone"
            v-model="form.phone"
            type="tel"
            placeholder="请输入电话号码"
            required
            :disabled="loading"
            class="form-input"
          />
        </div>

        <div class="form-group">
          <label for="password">密码</label>
          <input
            id="password"
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            required
            :disabled="loading"
            class="form-input"
          />
        </div>

        <div class="form-group">
          <label for="confirmPassword">确认密码</label>
          <input
            id="confirmPassword"
            v-model="form.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            required
            :disabled="loading"
            class="form-input"
          />
          <div v-if="passwordError" class="field-error">
            {{ passwordError }}
          </div>
        </div>

        <div v-if="error" class="error-message">
          {{ error }}
        </div>

        <button
          type="submit"
          :disabled="loading || !isFormValid"
          class="register-button"
        >
          <span v-if="loading" class="loading-spinner"></span>
          {{ loading ? '注册中...' : '注册' }}
        </button>
      </form>

      <div class="register-footer">
        <p>
          已有账户？
          <router-link to="/login" class="link">立即登录</router-link>
        </p>
        <p>
          <router-link to="/" class="link">返回首页</router-link>
        </p>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapGetters } from 'vuex'
import { currentAuthAPI } from '@/services/api'

export default {
  name: 'RegisterView',
  data() {
    return {
      form: {
        username: '',
        email: '',
        phone: '',
        password: '',
        confirmPassword: ''
      },
      usernameError: '',
      passwordError: ''
    }
  },
  computed: {
    ...mapGetters(['isLoading', 'authError']),
    loading() {
      return this.isLoading
    },
    error() {
      return this.authError
    },
    isFormValid() {
      return this.form.username &&
             this.form.email &&
             this.form.phone &&
             this.form.password &&
             this.form.confirmPassword &&
             this.form.password === this.form.confirmPassword &&
             !this.usernameError &&
             !this.passwordError
    }
  },
  watch: {
    'form.confirmPassword'() {
      this.validatePassword()
    },
    'form.password'() {
      this.validatePassword()
    }
  },
  methods: {
    ...mapActions(['register', 'clearError']),
    
    async handleRegister() {
      this.clearError()
      this.validatePassword()
      
      if (!this.isFormValid) {
        return
      }
      
      const result = await this.register({
        username: this.form.username,
        email: this.form.email,
        phone: this.form.phone,
        password: this.form.password
      })
      
      if (result.success) {
        // 注册成功，跳转到登录页面
        this.$router.push('/login')
        this.$message?.success('注册成功，请登录')
      }
    },
    
    async checkUsername() {
      if (!this.form.username) {
        this.usernameError = ''
        return
      }
      
      // 基本验证
      if (this.form.username.length < 3) {
        this.usernameError = '用户名至少需要3个字符'
        return
      }
      
      if (!/^[a-zA-Z0-9_]+$/.test(this.form.username)) {
        this.usernameError = '用户名只能包含字母、数字和下划线'
        return
      }
      
      try {
        const result = await currentAuthAPI.checkUsername(this.form.username)
        if (result.success && !result.data.available) {
          this.usernameError = '用户名已被使用'
        } else {
          this.usernameError = ''
        }
      } catch (error) {
        // 如果检查失败，不显示错误，让服务器端验证
        this.usernameError = ''
      }
    },
    
    validatePassword() {
      if (!this.form.password && !this.form.confirmPassword) {
        this.passwordError = ''
        return
      }
      
      if (this.form.password !== this.form.confirmPassword) {
        this.passwordError = '两次输入的密码不一致'
      } else if (this.form.password.length < 6) {
        this.passwordError = '密码至少需要6个字符'
      } else {
        this.passwordError = ''
      }
    }
  },
  mounted() {
    // 如果已经登录，直接跳转到首页
    if (this.$store.getters.isLoggedIn) {
      this.$router.push('/')
    }
  }
}
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.register-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 100%;
  max-width: 450px;
  animation: slideUp 0.6s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.register-header {
  text-align: center;
  margin-bottom: 30px;
}

.register-header h1 {
  color: #333;
  font-size: 28px;
  margin: 0 0 10px 0;
  font-weight: 600;
}

.register-header p {
  color: #666;
  font-size: 14px;
  margin: 0;
  line-height: 1.5;
}

.register-form {
  margin-bottom: 30px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-weight: 500;
  font-size: 14px;
}

.form-input {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  font-size: 16px;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-input:disabled {
  background-color: #f8f9fa;
  cursor: not-allowed;
}

.field-error {
  color: #c53030;
  font-size: 12px;
  margin-top: 4px;
}

.error-message {
  background-color: #fee;
  color: #c53030;
  padding: 12px 16px;
  border-radius: 8px;
  margin-bottom: 20px;
  font-size: 14px;
  border: 1px solid #feb2b2;
}

.register-button {
  width: 100%;
  padding: 14px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.register-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
}

.register-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid transparent;
  border-top: 2px solid currentColor;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.register-footer {
  text-align: center;
  border-top: 1px solid #e1e5e9;
  padding-top: 20px;
}

.register-footer p {
  margin: 8px 0;
  color: #666;
  font-size: 14px;
}

.link {
  color: #667eea;
  text-decoration: none;
  font-weight: 500;
  transition: color 0.3s ease;
}

.link:hover {
  color: #5a67d8;
  text-decoration: underline;
}

@media (max-width: 480px) {
  .register-container {
    padding: 10px;
  }
  
  .register-card {
    padding: 30px 20px;
  }
  
  .register-header h1 {
    font-size: 24px;
  }
}
</style>
